import Global from "@/Global";
import md5 from "js-md5";
import { Toast } from "vant";
import { getCompanyID, getPersonID } from "./session";
const appkey = "fd41fcc0400f66304a4d630b";
const random_str = "ie1r9flfvtrppyuq8p4tf9qtu";
const secret = 'e4025850fe8bd077b1d407ff';
let timestamp = new Date().getTime();
let signature = md5(`appkey=${appkey}&timestamp=${timestamp}&random_str=${random_str}&key=${secret}`);
let jim = window.JIM;
let context = null;
const myJmessage = {
	jim: jim,
	//初始化：jim初始化、登录、监听
	init() {
		if (!jim) { console.log('JIM is undefined '); return; }
		init();
		//login
		let personID = getPersonID();
		let companyID = getCompanyID();
		if (personID) {
			setTimeout(() => {
				this.login(personID);
			}, 1000);
		}
		if (companyID) {
			setTimeout(() => {
				this.login(companyID);
			}, 1000);

		}
		this.onMsgReceive();
	},
	//得到vue
	initContext: function (vue) {
		context = vue;
	},
	//登录，若用户不存在，则注册。登录成功，更新昵称
	login(username,nickname) {
		if (jim.isLogin()) {
			console.log('jim is login');
			return;
		}
		if (!jim.isInit()) {
			init();
			setTimeout(() => {
				myJmessage.login(username,nickname);
			}, 1000);
			return;
		}
		jim.login({
			'username': username,
			'password': '123456'
		}).onSuccess(function (data) {
			console.log(`jim登录成功，${data.code},${data.message}`)
			if(nickname != ""){
				myJmessage.updateSelfInfo(nickname);
			}
			//data.code 返回码
			//data.message 描述
			//data.online_list[] 在线设备列表
			//data.online_list[].platform  Android,ios,pc,web
			//data.online_list[].mtime 最近一次登录时间
			//data.online_list[].isOnline 是否在线 true or false
			//data.online_list[].isLogin 是否登录 true or false
			//data.online_list[].flag 该设备是否被当前登录设备踢出 true or false
		}).onFail(function (data) {
			//同上
			console.log(`jim登录失败，${data.code},${data.message}`)
			if (data.code == 880103) {
				//user not exist
				myJmessage.register(username,nickname);
			}
		});
	},
	//注册 ，注册成功则登录
	register(username,nickname) {
		jim.register({
			'username': username,
			'password': '123456',
			'nickname':nickname
		}).onSuccess(function (data) {
			//data.code 返回码
			//data.message 描述
			myJmessage.login(username,nickname);
		}).onFail(function (data) {
			// 同上
		});
	},
	//登出
	logout(){
		jim.loginOut();
	},
	//更新昵称
	updateSelfInfo(nickname) {
		if(!jim.isLogin()){
			return;
		}
		jim.updateSelfInfo({
			'nickname': nickname
		 }).onSuccess(function (data) {
			 console.log('jim update info success')
			//data.code 返回码
			//data.message 描述
		}).onFail(function (data) {
			//同上
			console.log('jim update info failure:'+data.message)
		});
	},
	//发送单聊消息
	sendMessage(userid, content) {
		//判断登录
		if (!jim.isLogin()) {
			myJmessage.login(userid);
			setTimeout(() => {
				myJmessage.sendMessage(userid, content);
			}, 1000);
		}
		else {
			// 发送消息
			jim.sendSingleMsg({
				target_username: userid,
				content: content,
			}).onSuccess(function (data, msg) {
				//data.code 返回码
				//data.message 描述
				//data.msg_id 发送成功后的消息 id
				//data.ctime_ms 消息生成时间,毫秒
				//data.appkey 用户所属 appkey
				//data.target_username 用户名
				//msg.content 发送成功消息体,见下面消息体详情
				console.log('jim message send success')
			}).onFail(function (data) {
				//data.code 返回码
				//data.message 描述
				console.log('jim message send failure:' + data.message)
			});
		}
	},
	//在线消息监听
	onMsgReceive() {
		jim.onMsgReceive(data => {
			let curRouteName = context.$route.name
			console.log(curRouteName);
			//企业
			if (curRouteName.indexOf('company') != -1) {
				if (curRouteName == 'company-im-window') {
					context.$bus.$emit(Global.bus_company_im_message_receive_InsidePage);
				}
				//其它外部页面
				else {
					context.$bus.$emit(Global.bus_company_im_message_receive_OutPage);
				}
			}
			//个人
			else if (curRouteName.indexOf('person') != -1) {
				if (curRouteName == 'person-im') {
					context.$bus.$emit(Global.bus_pereson_im_message_receive_InsidePage);
				}
				//其它外部页面
				else {
					context.$bus.$emit(Global.bus_pereson_im_message_receive_OutPage);
				}
			}
		})
	}
}

export default myJmessage;

//初始化
function init() {
	jim.init({
		"appkey": appkey,
		"random_str": random_str,
		"signature": signature,
		"timestamp": timestamp,
		"flag": 0
	}).onSuccess(function (data) {
		//data.code 返回码
		//data.message 描述
		console.log(`jmessage init success,code:${data.code},message:${data.message}`)
	}).onFail(function (data) {
		// 同上
		console.log(`jmessage init failure,code:${data.code},message:${data.message}`)
	});
}
